(function(){
	
	webUtils.nameSpace("wiseMen.formBuilder");
	
	wiseMen.formBuilder.currentEditCom;//当前编辑中的组件
	wiseMen.formBuilder=function(){
		var me=this;
		me.utilities={};
		
		me.init();
	};
	
	wiseMen.formBuilder.prototype.initUtilitiesPanel=function(){
		var me=this;
		$("#comTabBox").delegate(".utility","mousedown",function(md){
			var $target = $("#target");
		    var tar_pos = $target.position();
		    var $target_component = $("#target .component");
		    var tops = [];
		    
			md.preventDefault();
			
			var mouseX = md.pageX;
		    var mouseY = md.pageY;
			var $this=$(this);
			var utilData=$this.data("utility");
			var $temp=$('<form id="temp" class="am-form"></form>').append($this.find(".utility_temp").children().clone());
			$("body").append($temp);
			$temp.css({"position" : "absolute",
		        "top"      : mouseY - ($temp.height()/2) + "px",
		        "left"     : mouseX - ($temp.width()/2) + "px",
		        "opacity"  : "0.9"}).show();
			
			var half_box_height = ($temp.height()/2);
		    var half_box_width = ($temp.width()/2);
		    
		    $(document).delegate("body", "mousemove", function(mm){
		    	var mm_mouseX = mm.pageX;
		        var mm_mouseY = mm.pageY;
		        $temp.css({"top"      : mm_mouseY - half_box_height + "px",
		            "left"      : mm_mouseX - half_box_width  + "px"});
		        
		        if ( mm_mouseX > tar_pos.left &&
		                mm_mouseX < tar_pos.left + $target.width() + $temp.width()/2 &&
		                mm_mouseY > tar_pos.top &&
		                mm_mouseY < tar_pos.top + $target.height() + $temp.height()/2
		                ){
		        	$target.css("background-color", "#fafdff");
		            $target_component.css({"border-top" : "1px solid white", "border-bottom" : "none"});
		        	
		            tops = $.grep($target_component, function(e){
		                return ($(e).position().top -  mm_mouseY + half_box_height > 0 );
		              });
		            if (tops.length > 0){
		                $(tops[0]).css("border-top", "1px solid #22aaff");
		            } else{
		                if($target_component.length > 0){
		                  $($target_component[$target_component.length - 1]).css("border-bottom", "1px solid #22aaff");
		                }
		            }
		            
		        }else{
		        	$target.css("background-color", "#fff");
		            $target_component.css({"border-top" : "1px solid white", "border-bottom" : "none"});
		           
		        }
		    });
		    
		    $("body").delegate("#temp", "mouseup", function(mu){
		    	mu.preventDefault();

		        var mu_mouseX = mu.pageX;
		        var mu_mouseY = mu.pageY;
		        
		        $target_component.css({"border-top" : "1px solid white", "border-bottom" : "none"});
		        
		        if (mu_mouseX + half_box_width > tar_pos.left &&
		                mu_mouseX - half_box_width < tar_pos.left + $target.width() &&
		                mu_mouseY + half_box_height > tar_pos.top &&
		                mu_mouseY - half_box_height < tar_pos.top + $target.height()
		                ){
		        	
		        	$temp.attr("style", null);
		        	var $temp_content=$($temp.html()).addClass("component");
		        	if(tops.length > 0){
		        		$temp_content.insertBefore(tops[0]);
		            } else {
		            	$target.find("fieldset").append($temp_content);
		            }
		        	
		        	$temp_content.data("utility",utilData);
		        	var utilPlugin=me.utilities[utilData.type];
		        	if(utilPlugin.onAdd){
		        		utilPlugin.onAdd.call(null,$temp_content);
		        	}
		        }else{
		        	$target_component.css({"border-top" : "1px solid white", "border-bottom" : "none"});
		            tops = [];
		        }
		        
		        $target.css("background-color", "#fff");
		        $temp.remove();
		        
		        $("body").undelegate("#temp", "mouseup");
		        $(document).undelegate("body", "mousemove");
		    });
		    
		});
	};
	
	wiseMen.formBuilder.prototype.initTargetPanel=function(){
		$("#target").delegate(".component", "mousedown", function(md){
			md.preventDefault();
			
			var $target = $("#target");
		    var tar_pos = $target.position();
		    var $target_component = $("#target .component");
		    
			var tops = [];
		    var mouseX = md.pageX;
		    var mouseY = md.pageY;
		    var $this = $(this);
		    
		    var delayed = setTimeout(function(){//延迟拖拽，防止点击事件未发生。
		    	var $temp=$('<form id="temp" class="am-form"></form>').append($this);
	    	    
			    $("body").append($temp);
				$temp.css({"position" : "absolute",
			        "top"      : mouseY - ($temp.height()/2) + "px",
			        "left"     : mouseX - ($temp.width()/2) + "px",
			        "opacity"  : "0.9"}).show();
				
				var half_box_height = ($temp.height()/2);
			      var half_box_width = ($temp.width()/2);
				
				$(document).delegate("body", "mousemove", function(mm){
					var mm_mouseX = mm.pageX;
			        var mm_mouseY = mm.pageY;
			        $temp.css({"top"      : mm_mouseY - half_box_height + "px",
			            "left"      : mm_mouseX - half_box_width  + "px"});
			        
			        if ( mm_mouseX > tar_pos.left &&
			                mm_mouseX < tar_pos.left + $target.width() + $temp.width()/2 &&
			                mm_mouseY > tar_pos.top &&
			                mm_mouseY < tar_pos.top + $target.height() + $temp.height()/2
			                ){
			        	$target.css("background-color", "#fafdff");
			            $target_component.css({"border-top" : "1px solid white", "border-bottom" : "none"});
			        	
			            tops = $.grep($target_component, function(e){
			                return ($(e).position().top -  mm_mouseY + half_box_height > 0 );
			              });
			            if (tops.length > 0){
			                $(tops[0]).css("border-top", "1px solid #22aaff");
			            } else{
			                if($target_component.length > 0){
			                  $($target_component[$target_component.length - 1]).css("border-bottom", "1px solid #22aaff");
			                }
			            }
			            
			        }else{
			        	$target.css("background-color", "#fff");
			            $target_component.css({"border-top" : "1px solid white", "border-bottom" : "none"});
			           
			        }
				});
				
				$("body").delegate("#temp", "mouseup", function(mu){
					mu.preventDefault();

			        var mu_mouseX = mu.pageX;
			        var mu_mouseY = mu.pageY;
			        
			        $target_component.css({"border-top" : "1px solid white", "border-bottom" : "none"});
			        
			        if (mu_mouseX + half_box_width > tar_pos.left &&
			                mu_mouseX - half_box_width < tar_pos.left + $target.width() &&
			                mu_mouseY + half_box_height > tar_pos.top &&
			                mu_mouseY - half_box_height < tar_pos.top + $target.height()
			                ){
			        	
			        	$temp.attr("style", null);
			        	var $temp_content=$($temp.html()).addClass("component");
			        	if(tops.length > 0){
			        		$temp_content.insertBefore(tops[0]);
			            } else {
			            	$target.find("fieldset").append($temp_content);
			            }
			        }else{
			        	$target_component.css({"border-top" : "1px solid white", "border-bottom" : "none"});
			            tops = [];
			        }
			        
			        $target.css("background-color", "#fff");
			        $temp.remove();
			        
			        $("body").undelegate("#temp", "mouseup");
			        $(document).undelegate("body", "mousemove");
				});
		    },300);
		    
		    $(document).mouseup(function () {
		      clearInterval(delayed);
		      return false;
		    });
		    
			$this.mouseout(function () {
		      clearInterval(delayed);
		      return false;
		    });
			
		});
	};
	
	wiseMen.formBuilder.prototype.addUtility=function(util){
		util=util||{
			type:"text",
			opt:{},//自定义属性写在这里。包括默认属性也写在这里。
			menu:{
				title:"文本输入框",
				cls:"formOption_text"
			},
			tempHtml:'<div class="am-form-group">'
				+'<label>文本名称</label>'
				+'<input type="text" class="am-input-sm" placeholder="文本内容">'
				+'<p class="am-form-help">帮助说明...</p>'
				+'</div>'
		}
		this.utilities[util.type]=util;
		
		var utilHtml='<li class="utility" title="点击选择或拖动到左侧">'
			+'<span class="title">'+util.menu.title+'</span>'
			+'<span class="formOption '+util.menu.cls+'"></span>'
			+'<div class="utility_temp" style="display: none;">'
			+ util.tempHtml
			+'</div>'
			+'</li>';
		utilHtml=$(utilHtml);
		utilHtml.data("utility",util);
		
		$("#comTabBox .utilityCol").append(utilHtml);
	}
	
	wiseMen.formBuilder.prototype.initComponentOnClick=function(){
		var me=this;
		$("#target").delegate(".component", "click", function(md){
			var $this=$(this);
			wiseMen.formBuilder.currentEditCom=$this;
			var utilData=$this.data("utility");
			var utilPlugin=me.utilities[utilData.type];
			if(utilPlugin.editPageTemp){
				$("#comTabBox").data('amui.tabs').open($("#editPanel"));
				$("#comEditPanel").load(ctx+utilPlugin.editPageTemp,{},function(){
					if(utilPlugin.onEdit){
		        		utilPlugin.onEdit.call(null,$this);
		        	}
				});
			}
        	
		});
	}
	
	wiseMen.formBuilder.prototype.init=function(){
		this.initUtilitiesPanel();
		this.initTargetPanel();
		this.initComponentOnClick();
	};
})();

/**
 * 组件拖拽功能
 */
var formBuilder
$(function(){
	formBuilder=new wiseMen.formBuilder();
	
});